import React from "react"

import Topic from "./components/Topic"
import List from "./components/List"
import Recommend from "./components/Recommend"
import Writer from "./components/Writer"
import { connect } from "react-redux"
import { getHomeInfo, toggleTopShow } from "./actionCreators"

import { HomeWrapper, HomeLeft, HomeRight, BackTop } from "./style"

import banner from "../../statics/banner.jpg"

class Home extends React.PureComponent {
  componentDidMount() {
    this.props.changeHomeData()
    this.bindEvents()
  }

  handleBackTop = () => {
    // 滚动条距离文档顶部的距离
    let topDistance = document.documentElement.scrollTop
    // 用于存放 requestAnimationFrame 所返回的 id
    let timer = null
    //帧数 - 300 为 300ms 也指 300ms 内完成动画
    let time = 300 / 16
    //每帧所移动的长度
    let lengthPreFrame = topDistance / time
    requestAnimationFrame(function move() {
      // 重新获取距离文档顶部的距离,用于判断是否取消 requestAnimationFrame 的执行
      let top = document.documentElement.scrollTop
      if (top > 0) {
        document.documentElement.scrollTop -= lengthPreFrame
        timer = requestAnimationFrame(move)
      } else {
        cancelAnimationFrame(timer)
      }
    })
  }

  // 将一些页面渲染过后需要绑定与监听的事件放在这里
  bindEvents = () => {
    window.addEventListener("scroll", this.props.changeScrollTopShow)
  }

  // 当组件从页面中卸载时，将 window 的 scroll 事件移除

  componentWillMount() {
    window.removeEventListener("scroll", this.props.changeScrollTopShow)
  }

  // shouldComponentUpdate(preState,preProps){
  //   if(this.state === preState && this.props === preProps)
  //     return false
  // }

  render() {
    return (
      <HomeWrapper>
        <HomeLeft>
          <img className="banner-img" src={banner} alt="" />
          <Topic />
          <div className="split-line" />
          <List />
        </HomeLeft>
        <HomeRight>
          <Recommend />
          <Writer />
        </HomeRight>
        {this.props.showScroll && (
          <BackTop onClick={this.handleBackTop}>顶部</BackTop>
        )}
      </HomeWrapper>
    )
  }
}

const mapState = state => ({
  showScroll: state.getIn(["home", "showScroll"])
})

const mapDispatch = dispatch => ({
  changeHomeData: () => {
    dispatch(getHomeInfo())
  },
  changeScrollTopShow: () => {
    if (document.documentElement.scrollTop > 400) {
      dispatch(toggleTopShow(true))
    } else {
      dispatch(toggleTopShow(false))
    }
  }
})

export default connect(
  mapState,
  mapDispatch
)(Home)
